from django.shortcuts import render
from PIL import Image
import pytesseract

tesseract_cmd = r'D:\Tessercat-OCR\tesseract'
pytesseract.pytesseract.tesseract_cmd = tesseract_cmd


def not_empty(s):
    return s and s.strip()


def get_bingli(request):
    if request.method == 'GET':
        return render(request, 'bingli.html')
    elif request.method == "POST":
        # 获取请求参数
        photo = request.FILES.get('photo', '')
        print(photo.name)
        import os
        if not os.path.exists('media'):
            os.makedirs('media')
        with open(os.path.join('web/media', photo.name), 'wb') as fw:
            # 一次性读取文件
            fw.write(photo.read())
            # 分块读取文件
            # for w in photo.chunks():
            #     fw.write(w)
        # 至此 media 文件目录下已经有了名为 photo.name 的图片文件
        image = Image.open(os.path.join('web/media', photo.name))
        bingli_content = pytesseract.image_to_string(image, lang='chi_sim')
        content_list = bingli_content.split('\n')
        for index in range(len(content_list)):
            content_list[index] = content_list[index].strip()
        for i in content_list:
            content_list.remove('')
        t = filter(not_empty, content_list)
        result_list = list(t)
        result_list2 = result_list
        for element in result_list:
            i = result_list.index(element)
            result_list2[i] = element.replace(" ", "")
        text = {
            'bingli_content': result_list
        }
        return render(request, 'bingli.html', text)
